package com.luoyuanxiangvip.core.config;

import com.google.gson.Gson;
import com.luoyuanxiangvip.common.enums.ConfigEnum;
import com.luoyuanxiangvip.common.vo.QiNiuYun;
import com.luoyuanxiangvip.core.service.IConfigService;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 七牛云上传
 * </p>
 *
 * @author luoyuanxiang <p>luoyuanxiangvip.com</p>
 * @since 2019/6/3
 */
@Component
public class QiniuConfig {

    @Resource
    private IConfigService iConfigService;

    private QiNiuYun config() {
        return iConfigService.getValue(ConfigEnum.QI_NIU_YUN.getKey());
    }

    private Auth auth() {
        return Auth.create(config().getQiniuAccessKey(), config().getQiniuSecretKey());
    }

    private Configuration configuration() {
        //构造一个带指定Zone对象的配置类
        return new Configuration(Zone.zone1());
    }

    private BucketManager bucketManager() {
        return new BucketManager(auth(), configuration());
    }

    /**
     * 文件上传
     *
     * @param file  图片
     * @param isAll 是否返回图片全路径
     *              true 图片全路径（http://img.luoyuanxiangvip.com/20180920/3dfc654eeaeb41e695a7a1e039295de7）
     *              false （20180920/3dfc654eeaeb41e695a7a1e039295de7）
     * @return url
     * @throws QiniuException QiniuException
     */
    public String upload(MultipartFile file, Boolean isAll) throws Exception {
        String fileName = System.currentTimeMillis() + ".jpg";
        String key = config().getQiniuFileName() + "/" + fileName;
        String upToken = auth().uploadToken(config().getQiniuBucketName());
        Response response = new UploadManager(configuration()).put(file.getBytes(), key, upToken);
        //解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        return isAll ? config().getQiuniuBasePath() + "/" + putRet.key : putRet.key;
    }

    /**
     * 文件删除
     *
     * @param key 文件名称 如（20180920/3dfc654eeaeb41e695a7a1e039295de7）
     */
    public void delete(String key) throws QiniuException {
        bucketManager().delete(config().getQiniuBucketName(), key);
    }


    /**
     * 获取所有文件
     * @return List
     */
    public List<FileInfo> fileList() {
        //文件名前缀
        String prefix = "";
        //每次迭代的长度限制，最大1000，推荐值 1000
        int limit = 1000;
        //指定目录分隔符，列出所有公共前缀（模拟列出目录效果）。缺省值为空字符串
        String delimiter = "";
        //列举空间文件列表
        BucketManager.FileListIterator fileListIterator = bucketManager().createFileListIterator(config().getQiniuBucketName(), prefix, limit, delimiter);
        List<FileInfo> fileInfos = null;
        while (fileListIterator.hasNext()) {
            //处理获取的file list结果
            fileInfos = Arrays.asList(fileListIterator.next());
        }
        assert fileInfos != null;
        return fileInfos.stream().filter(fileInfo ->
                "image/jpeg".equals(fileInfo.mimeType)
                        || "image/png".equals(fileInfo.mimeType)
                        || "image/jpg".equals(fileInfo.mimeType)
                        || "image/bmp".equals(fileInfo.mimeType)
        ).collect(Collectors.toList());
    }
}
